package com.api.syh56.shengyunhui.service.impl;

import com.api.syh56.shengyunhui.common.BaseUserInfo;
import com.api.syh56.shengyunhui.common.Constants;
import com.api.syh56.shengyunhui.common.UserInfoEnu;
import com.api.syh56.shengyunhui.entity.Invoice;
import com.api.syh56.shengyunhui.entity.InvoiceTitle;
import com.api.syh56.shengyunhui.entity.Waybill;
import com.api.syh56.shengyunhui.entity.dto.InvoiceDTO;
import com.api.syh56.shengyunhui.exception.BaseException;
import com.api.syh56.shengyunhui.mapper.InvoiceMapper;
import com.api.syh56.shengyunhui.service.*;
import com.api.syh56.shengyunhui.util.CommonUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class InvoiceServiceImpl extends ServiceImpl<InvoiceMapper,Invoice> implements InvoiceService {
    @Autowired
    private InvoiceMapper iMapper;

    @Autowired
    private WayBillService wayBillService;

    @Autowired
    private InvoiceTitleService invoiceTitleService;

    @Override
    public void insert(InvoiceDTO invoiceDTO) {
//        Long titleId = invoiceDTO.getTitleId();
//        QueryWrapper<InvoiceTitle> invoiceTitleQueryWrapper = new QueryWrapper<>();
//        invoiceTitleQueryWrapper.lambda().eq(InvoiceTitle::getId,titleId);
//        InvoiceTitle title = invoiceTitleService.getOne(invoiceTitleQueryWrapper);
//        String[] wids = invoiceDTO.getWid();
//        String wid = arraytoString(wids);
//        String id = BaseUserInfo.get(UserInfoEnu.id.getCode());
//
//        BigDecimal sum = BigDecimal.ZERO;
//        for (String s : wids) {
//            Long aLong = Long.valueOf(s);
//            System.out.println("along:" + aLong);
//            QueryWrapper<Waybill> wrapper = new QueryWrapper<>();
//            wrapper.lambda().eq(Waybill::getId, aLong);
//            Waybill waybill = wayBillService.getOne(wrapper);
//            System.out.println("waybill:" + waybill);
//            BigDecimal offerEnd = waybill.getOfferEnd();
//            sum = sum.add(offerEnd);
//        }
//
//        Invoice invoice = Invoice.builder()
//                .widList(wid)
//                .uid(Long.valueOf(id))
//                .unitPrice(sum)
//                .goodsNum(1)
//                .unit(Constants.unit.COPIES)
//                .build();
//
//        BeanUtils.copyProperties(title,invoice);
//
//        invoice.setUnitPrice(sum);
//        BigDecimal unitPrice = invoice.getUnitPrice();
//        invoice.setGoodsNum(1);
//        invoice.setUnit(Constants.unit.COPIES);
//        double goodsNum = invoice.getGoodsNum();
//        invoice.setUAmount(unitPrice.multiply(BigDecimal.valueOf(goodsNum)));
//        BigDecimal uAmount = invoice.getUAmount();
//        System.out.println("总金额："+uAmount);
//
//        invoice.setTaxRate(Constants.taxRate.NINE);
//
//        System.out.println("税率"+invoice.getTaxRate());
//        invoice.setTaxAmount(uAmount.multiply(invoice.getTaxRate()));
//        BigDecimal taxAmount = invoice.getTaxAmount();
//        invoice.setTotalAmount(uAmount.add(taxAmount));
//        iMapper.insert(invoice);
    }



    @Override
    @Transactional
    public void insertNew(InvoiceDTO invoiceDTO) {
//        Long titleId = invoiceDTO.getTitleId();
//        InvoiceTitle title = invoiceTitleService.getById(titleId);
        //开票DTO中获取发票抬头
        InvoiceTitle invoiceTitle = invoiceDTO.getInvoiceTitle();

        String[] wids = invoiceDTO.getWid();
//        String widStr = invoiceDTO.getWid();
//        String[] wids = widStr.split(",");
        String wid = arraytoString(wids);
        String id = BaseUserInfo.get(UserInfoEnu.id.getCode());
        if (invoiceDTO.getInvoiceWay() == 0) {
            for (String str : wids){
                System.out.println("str:"+str);

                //更新该订单的开票状态
                Waybill waybill = wayBillService.getById(Long.valueOf(str));
                waybill.setInvoiced(true);
                wayBillService.updateById(waybill);


                Invoice invoice = Invoice.builder().widList(str)
                        .uid(Long.valueOf(id))
                        .taxRate(Constants.taxRate.NINE)
                        .goodsNum(1)
                        .invoiceContent(invoiceDTO.getInvoiceContent())
//                        .titleId(invoiceTitle.getId())
                        .postscript(invoiceDTO.getPostscript())
                        .mailbox(invoiceDTO.getMailbox())
                        .totalAmount(waybill.getOfferAll())
                        .taxAmount(waybill.getTax())
                        .uAmount(waybill.getOfferendMinusTax())
                        .unit(Constants.unit.COPIES)
                        .invoiceState(Constants.invoiceState.APPLIED)
                        .invoiceType(Constants.invoiceType.SPECIAL_TICKET)
                        .build();

                //抬头信息复制到发票
                BeanUtils.copyProperties(invoiceTitle,invoice);

                //uid被invoiceTitle覆盖掉了，需要重新设置一遍uid
                invoice.setUid(Long.valueOf(id));

                CommonUtil.setIdToNull(invoice);
                iMapper.insert(invoice);

            }
        } else if (invoiceDTO.getInvoiceWay() == 1) {
            BigDecimal offerend_sum = BigDecimal.ZERO;
            BigDecimal tax_sum = BigDecimal.ZERO;
            BigDecimal offerendPlusTax_sum = BigDecimal.ZERO;
            Integer goodsNum = 0;
            for (String str : wids) {

                //更新该订单的开票状态
                Waybill waybill = wayBillService.getById(Long.valueOf(str));
                waybill.setInvoiced(true);
                wayBillService.updateById(waybill);

                System.out.println("waybill:" + waybill);
                offerend_sum = offerend_sum.add(waybill.getOfferAll());
                tax_sum = tax_sum.add(waybill.getTax());
                offerendPlusTax_sum = offerendPlusTax_sum.add(waybill.getOfferendMinusTax());
                goodsNum++;
            }



            Invoice invoice = Invoice.builder().widList(wid)
                    .uid(Long.valueOf(id))
                    .taxRate(Constants.taxRate.NINE)
                    .goodsNum(goodsNum)
                    .mailbox(invoiceDTO.getMailbox())
                    .invoiceContent(invoiceDTO.getInvoiceContent())
//                    .titleId(invoiceTitle.getId())
                    .postscript(invoiceDTO.getPostscript())
                    .totalAmount(offerend_sum)
                    .taxAmount(tax_sum)
                    .uAmount(offerendPlusTax_sum)
                    .unit(Constants.unit.COPIES)
                    .invoiceState(Constants.invoiceState.APPLIED)
                    .invoiceType(Constants.invoiceType.SPECIAL_TICKET)
                    .build();

            //抬头信息复制到发票
            BeanUtils.copyProperties(invoiceTitle,invoice);

            //uid被invoiceTitle覆盖掉了，需要重新设置一遍uid
            invoice.setUid(Long.valueOf(id));

            CommonUtil.setIdToNull(invoice);
            System.out.println(invoice);
            iMapper.insert(invoice);
        }
    }

    private String arraytoString(String[] array) {
        if (array == null) {
            return "";
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0;i<array.length;i++){
            stringBuilder.append(array[i]);
            if (i < array.length-1) {
                stringBuilder.append(",");
            }
        }
        return stringBuilder.toString();
    }



    @Override
    public void deleteById(Long id) {
        if (id == null) {
            throw new BaseException("id不存在");
        }
        iMapper.deleteById(id);
    }

    @Override
    public List<Invoice> selectAll() {
        return iMapper.selectList(null);
    }

    @Override
    public Invoice selectBy(Long id) {
        if (id == null) {
            throw new BaseException("id不存在");
        }
        Invoice invoice = iMapper.selectById(id);
        return invoice;
    }

    @Override
    public void insertUrl(Invoice invoice) {
        Invoice invoiceDB = getById(invoice.getId());

        invoiceDB.setInvoiceUrl(invoice.getInvoiceUrl());
        invoiceDB.setInvoiceNum(invoice.getTaxNum());
        invoiceDB.setInvoiceState(Constants.invoiceState.INVOICED);
        invoiceDB.setIssuingTime(LocalDateTime.now());

        log.info(invoiceDB.toString());

        updateById(invoiceDB);
    }


}
